<template>
  <div class="app-container">
    <div class="form-box">
      <el-form ref="form" :model="form" label-width="120px" :rules="rules">
        <el-tabs type="border-card" class="form-tabs">
          <el-tab-pane :label="$t('common.edit_info')" class="form-tabs-tab-pane">
            <!-- 广告名称 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('ads.name')" prop="name">
                  <el-input v-model="form.name" :placeholder="$t('common.pleaseFill')+$t('ads.name')" clearable />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 广告图片 -->
            <el-row v-if="adsSpace.type==1" :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item
                  :label="$t('ads.cover_image')"
                  prop="cover_image"
                  :rules="{ required: (adsSpace.type==1), message: $t('ads.cover_image_tips'), trigger: 'blur' }"
                >
                  <jsp-image-upload
                    :title="$t('ads.cover_image')"
                    :default-list="cover_imageList"
                    :action="fileUploadConfig.imageAction"
                    :headers="fileUploadConfig.headers"
                    :size="Number(fileUploadConfig.allowImageSize)"
                    :accept="fileUploadConfig.allowImageTypeList"
                    :width="Number(adsSpace.width)"
                    :height="Number(adsSpace.height)"
                    @error="(error)=>{error!=null && $message.error(error)}"
                    @change="handleImageUploadChange"
                    @remove="handleImageDelete"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 投放周期 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('ads.cast_period')" prop="cast_period">
                  <el-radio-group v-model.number="form.cast_period" :disabled="routerParams.id>0" :placeholder="$t('ads.cast_period_tips')">
                    <el-radio v-for="item in dictionaryService.getItems('adsCastPeriodVar')" :key="item.id" :label="Number(item.value)">{{ item.name }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 投放开始时间-投放结束时间 -->
            <el-row
              v-if="form.cast_period == 2"
              :gutter="20"
              type="flex"
              justify="center"
            >
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <!-- 日期范围 -->
                <el-form-item
                  :label="$t('ads.cast_time')"
                  :rules="{required: form.cast_period==2, message:$t('ads.cast_time_tips'), trigger: 'blur'}"
                  prop="castDatetimerange"
                >
                  <el-date-picker
                    v-model="form.castDatetimerange"
                    type="datetimerange"
                    :range-separator="$t('common.rangeTo')"
                    :start-placeholder="$t('common.start_time')"
                    :end-placeholder="$t('common.end_time')"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    format="yyyy-MM-dd HH:mm:ss"
                    clearable
                    :editable="false"
                    @change="timeChange"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 链接地址 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('common.href')" prop="href">
                  <el-input
                    v-model="form.href"
                    :placeholder="$t('common.pleaseFill')+$t('common.href')"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 打开方式 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item
                  :label="$t('common.href_target')"
                  prop="href_target"
                >
                  <el-select
                    v-model="form.href_target"
                    :placeholder="$t('common.href_target_tips')"
                    clearable
                  >
                    <el-option
                      v-for="item in dictionaryService.getItems('hrefTargetTypeVar')"
                      :key="item.id"
                      :label="item.name"
                      :value="item.value"
                    />

                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 链接关系XFN -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('common.rel')" prop="rel">
                  <el-select
                    v-model="form.rel"
                    :placeholder="$t('common.rel_tips')"
                    clearable
                  >
                    <el-option
                      v-for="item in dictionaryService.getItems('relTypeVar')"
                      :key="item.id"
                      :label="item.name"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 客户名称 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('ads.partner')" prop="partner">
                  <el-input
                    v-model="form.partner"
                    :placeholder="$t('ads.partner_tips')"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 联系人 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item
                  :label="$t('ads.partner_linkman')"
                  prop="partner_linkman"
                >
                  <el-input
                    v-model="form.partner_linkman"
                    :placeholder="$t('ads.partner_linkman_tips')"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 联系电话 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item
                  :label="$t('ads.partner_phone_number')"
                  prop="partner_phone_number"
                >
                  <el-input
                    v-model="form.partner_phone_number"
                    :placeholder="$t('ads.partner_phone_number_tips')"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 备注 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item
                  :label="$t('ads.description')"
                  prop="description"
                >
                  <el-input
                    v-model="form.description"
                    type="textarea"
                    :placeholder="$t('ads.description_tips')"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 发布状态 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item
                  :label="$t('common.status')"
                  prop="status"
                >
                  <el-select
                    v-model.number="form.status"
                    :placeholder="$t('common.pleaseSelect')+$t('common.status')"
                    clearable
                  >
                    <el-option
                      v-for="item in dictionaryService.getItems('statusVar')"
                      :key="item.id"
                      :label="item.name"
                      :value="Number(item.value)"
                    />

                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>

        <el-row :gutter="20" type="flex" justify="center" class="btn-row">
          <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
            <el-form-item>
              <el-button
                type="primary"
                :loading="submitLoading"
                :disabled="routerParams.id>0&&!checkPermission(['admin.ads.update']) || !routerParams.id&&!checkPermission(['admin.ads.store'])"
                @click="onSubmit"
              >{{ $t('common.submit') }}</el-button>
              <el-button @click="onCancel">{{ $t('common.cancel') }}</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import JspImageUpload from '@/components/JspImageUpload'
import { mapGetters } from 'vuex'
import { show, update, store } from '@/api/ads'
import { loadingStart } from '@/utils/loading-service'
import { getAdsSpaceConfig } from '@/api/ads-space'
import checkPermission from '@/utils/permission'

// export
export default {
  name: 'AdsEdit',
  components: {
    JspImageUpload
  },
  data() {
    return {
      submitLoading: false,
      form: {
        name: '',
        cover_image: 0,
        href: '',
        href_target: '_self',
        rel: '',
        partner: '',
        partner_linkman: '',
        partner_phone_number: '',
        description: '',
        cast_period: 1,
        start_time: '',
        end_time: '',
        status: 1,
        castDatetimerange: null
      },
      cover_imageList: [],
      rules: {
        name: [
          { required: true, message: this.$t('ads.name_tips'), trigger: 'blur' },
          { min: 2, max: 50, message: this.$t('ads.name_length_tips'), trigger: 'blur' }
        ]
      },
      // 路由参数
      routerParams: {},
      back_route_name: 'AdsIndex',
      back_route_params: {},
      adsSpace: {}
    }
  },
  computed: {
    ...mapGetters(['fileUploadConfig'])
  },
  created() {
    this.routerParams = this.$route.params
    this.back_route_params = { space_id: this.routerParams.space_id }
  },
  mounted() {
    this.getDetail()
  },
  methods: {
    checkPermission,
    async getDetail() {
      const { space_id, id } = this.routerParams
      const loading = loadingStart()
      if (id > 0) {
        await show(space_id, id).then((response) => {
          for (const key in response.data) {
            if (key in this.form) {
              this.form[key] = response.data[key]
            }
          }
        }).catch(() => {
          this.closeBack(this.back_route_name, this.back_route_params)
        })

        // 封面图
        this.cover_imageList = this.form.cover_image
        this.form.cover_image = this.form.cover_image.map((item) => {
          return item.id
        }).join(',')

        // 时间段
        if (this.form.start_time && this.form.end_time) {
          this.form.castDatetimerange = [
            this.form.start_time,
            this.form.end_time
          ]
        }
      }
      await getAdsSpaceConfig(space_id).then((response) => {
        this.adsSpace = response.data
      }).catch(() => {
        this.closeBack(this.back_route_name, this.back_route_params)
      })
      loading.close()
    },
    onSubmit() {
      this.$refs['form'].validate(async(valid) => {
        if (valid) {
          this.submitLoading = true
          let response
          const newForm = JSON.parse(JSON.stringify(this.form))
          delete newForm.castDatetimerange
          if (this.routerParams.id) {
            response = await update(this.routerParams.space_id, this.routerParams.id, newForm).catch(() => {})
          } else {
            response = await store(this.routerParams.space_id, newForm).catch(() => {})
          }
          if (response instanceof Object) {
            this.$message.success(response.message)
            this.closeBack(this.back_route_name, this.back_route_params)
          }
          this.submitLoading = false
        } else {
          this.$message.error(this.$t('common.pleaseFillRequired'))
          return false
        }
      })
    },
    onCancel() {
      this.closeBack(this.back_route_name, this.back_route_params)
    },
    handleImageUploadChange(result) {
      this.form.cover_image = result.ids
      this.$refs['form'].validateField(['cover_image'])
      this.form.cover_image && this.$refs['form'].clearValidate(['cover_image'])
    },
    handleImageDelete(file, fileList) {
      this.$refs['form'].validateField(['cover_image'])
    },
    // 投放时间范围选择
    timeChange(e) {
      this.form.start_time = (e && e[0]) || ''
      this.form.end_time = (e && e[1]) || ''
    }
  }
}
</script>

<style scoped lang="scss">
</style>
